//
//  SpotViewController.m
//  hai游～
//
//  Created by jakf_17 on 15/5/23.
//  Copyright (c) 2015年 jakf_17. All rights reserved.
//

#import "SpotViewController.h"
#import "CountryDetailImageView.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <AFNetworking/AFNetworking.h>
#import "SpotImageCell.h"
#import "SpotLabelCell.h"
#import "ReViewsCell.h"
#import "SpotModel.h"
#import "SpotSeparaCell.h"
#import "TravelsForThisSpotViewController.h"
#import "TravelNotesDetailViewController.h"
@interface SpotViewController ()<UITableViewDataSource, UITableViewDelegate>

@end

@implementation SpotViewController


- (void)dealloc
{
    [_tableView release];
    [_model release];
    [_dic release];
    [_array release];
    [_imageView release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.array = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createMyTableView];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    [manager.requestSerializer setValue:@"BreadTrip/android/5.1.0/zh (android OS4.4.4) lte26007 Map/GoogleMap/v1 (HM 2A,Xiaomi) Paros/3.2.13" forHTTPHeaderField:@"User-Agent"];
    
    NSString *website = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@/", self.model.type, self.model.destinationId];

    
    [manager GET:website parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        self.dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        
        [self creatArrayWithDic];
        [self createImageView];
        [_tableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
    }];
}
- (void)creatArrayWithDic
{
    NSDictionary *dic = [_dic objectForKey:@"impressions"];
    NSArray *trips = [dic objectForKey:@"trips"];
    for (NSDictionary *subDic in trips) {
        SpotModel *model = [[SpotModel alloc] init];
        [model setValue:subDic forKey:@"trip"];
        model.type = @"1";
        [_array addObject:model];
        [model release];
    }
    NSArray *reviews = [dic objectForKey:@"reviews"];
    for (NSDictionary *subDic in reviews) {
        SpotModel *model = [[SpotModel alloc] init];
        [model setValue:subDic forKey:@"review"];
        model.type = @"2";
        [_array addObject:model];
        [model release];
    }
    NSString *str = @"基本信息";
    SpotModel *spotModel = [[SpotModel alloc] init];
    spotModel.type = @"4";
    spotModel.str = str;
    [_array addObject:spotModel];
    [spotModel release];
    NSArray *array = @[@"概况", @"地址", @"到达方式", @"开放时间", @"联系方式"];
    for (int i = 0; i < array.count; i++) {
        SpotModel *model = [[SpotModel alloc] init];
        [model setValuesForKeysWithDictionary:_dic];
        model.introduce = array[i];
        model.type = @"3";
        [_array addObject:model];
        [model release];
    }
    
}
- (void)createMyTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake( 0, 0, [[UIScreen mainScreen] bounds].size.width, self.view.frame.size.height - 64)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 360)];
    [self.view addSubview:_headerView];
    [_headerView release];
    _tableView.tableHeaderView = _headerView;
    [self.view addSubview:_tableView];
    [_tableView release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _array.count;
}
#pragma mark - 
#pragma mark TableView创建－－－
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SpotModel *model = [_array objectAtIndex:indexPath.row];
    if ([model.type isEqualToString:@"1"]) {
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
        NSDictionary *trip = model.trip;
        NSString *content = [trip objectForKey:@"trip_text"];
        if (content != nil) {
            
       
        CGRect rect = [content boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width - 10, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return 136 + rect.size.height;
        } else {
            return 136;
        }
    }
    if ([model.type isEqualToString:@"2"]) {
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
        NSDictionary *review = model.review;
        NSString *content = [review objectForKey:@"content"];
        if (content != nil) {
            
       
        CGRect rect = [content boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width - 10, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return 50 + rect.size.height;
        } else {
            return 50;
        }
    }
    if ([model.type isEqualToString:@"3"]) {
        NSString *str = model.introduce;
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
        if ([str isEqualToString:@"概况"]) {
            NSString *content = model.spotDescription;
            if (content != nil) {
                
            
           CGRect rect = [content boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width - 10, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            return rect.size.height + 40;
            } else {
                return 40;
            }
        } else if ([str isEqualToString:@"地址"]) {
            NSString *content = model.address;
            if (content != nil) {
                
            
            CGRect rect = [content boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width - 10, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            return rect.size.height + 40;
            } else {
                return 40;
            }
        } else if ([str isEqualToString:@"到达方式"]) {
            NSString *content = model.arrival_type;
            if (content != nil) {
                
            
            CGRect rect = [content boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width - 10, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            return rect.size.height + 40;
            } else {
                return 40;
            }
        } else if ([str isEqualToString:@"开放时间"]) {
            NSString *content = model.opening_time;
            if (content != nil) {
                
            
            CGRect rect = [content boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width - 10, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            return rect.size.height + 40;
            } else {
                return 40;
            }
        } else if ([str isEqualToString:@"联系方式"]) {
            NSString *content = model.tel;
            if (content != nil) {
                
            
            CGRect rect = [content boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width - 10, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            return rect.size.height + 40;
            } else {
                return 40;
            }
        }
    }
    else if ([model.type isEqualToString:@"4"]) {
        return 120;
    }
    return 30;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *trip = @"trip";
    static NSString *review = @"review";
    static NSString *textCell = @"textCell";
    static NSString *separator = @"separator";
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    SpotModel *model = [_array objectAtIndex:indexPath.row];
    if ([model.type isEqualToString:@"1"]) {
        SpotImageCell *cell = [tableView dequeueReusableCellWithIdentifier:trip];
        if (cell == nil) {
            cell = [[[SpotImageCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:trip] autorelease];
        }
        NSDictionary *bigTrip = model.trip;
        NSDictionary *trip = [bigTrip objectForKey:@"trip"];
        cell.label.text = [bigTrip objectForKey:@"trip_text"];
        cell.dateLabel.text = [trip objectForKey:@"datetime"];
        NSDictionary *user = [trip objectForKey:@"user"];
        NSString *avatar_s = [user objectForKey:@"avatar_l"];
        [cell.userImage sd_setImageWithURL:[NSURL URLWithString:avatar_s] placeholderImage:image];
        cell.userName.text = [user objectForKey:@"name"];
        NSString *text = [trip objectForKey:@"name"];
        NSString *name = [NSString stringWithFormat:@"@%@", text];
        cell.userSum.text = name;
        cell.labelBlock = ^(NSInteger trip_id) {
            TravelNotesDetailViewController *detailNotes = [[TravelNotesDetailViewController alloc] init];
            detailNotes.webId = [NSString stringWithFormat:@"%ld", trip_id];
            [self.navigationController pushViewController:detailNotes animated:YES];
            [detailNotes release];
        };
        NSArray *photoArray = [bigTrip objectForKey:@"waypoints"];
        cell.scroll.contentSize = CGSizeMake(115 * photoArray.count, 80);
        for (int i = 0; i < photoArray.count; i++) {
            NSDictionary *dic = photoArray[i];
            NSNumber *detailImageId = [dic objectForKey:@"id"];
            NSNumber *trip_id = [dic objectForKey:@"trip_id"];
            cell.userSum.tag = trip_id.integerValue;
            NSString *imagePath = [dic objectForKey:@"photo"];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * 115, 0, 110, 80)];
            imageView.tag = detailImageId.integerValue;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [imageView addGestureRecognizer:tap];
            [tap release];
            [imageView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:image];
            [cell.scroll addSubview:imageView];
            [imageView release];
        }
        return cell;
    }
     else if ([model.type isEqualToString:@"2"]) {
        ReViewsCell *cell = [tableView dequeueReusableCellWithIdentifier:review];
        if (cell == nil) {
            cell = [[[ReViewsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:review] autorelease];
        }
         NSDictionary *review = model.review;
         cell.contentLabel.text = [review objectForKey:@"content"];
         NSDictionary *user = [review objectForKey:@"user"];
         cell.userName.text = [user objectForKey:@"name"];
         [cell.userImage sd_setImageWithURL:[NSURL URLWithString:[user objectForKey:@"avatar_l"]] placeholderImage:image];
         
        return cell;
    }
    else  if ([model.type isEqualToString:@"3"]){
        SpotLabelCell *cell = [tableView dequeueReusableCellWithIdentifier:textCell];
        if (cell == nil) {
            cell = [[[SpotLabelCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:textCell] autorelease];
        }
        cell.titileLabel.text = model.introduce;
        if ([model.introduce isEqualToString:@"概况"]) {
            cell.contentLabel.text = model.spotDescription;
            if(model.spotDescription.length == 0) {
                cell.contentLabel.text = @"暂无";
            }
        } else if([model.introduce isEqualToString:@"地址"]) {
            cell.contentLabel.text = model.address;
            if (model.address.length == 0) {
                cell.contentLabel.text = @"暂无";
            }
        } else if([model.introduce isEqualToString:@"到达方式"]) {
            cell.contentLabel.text = model.arrival_type;
            if (model.arrival_type.length == 0) {
                cell.contentLabel.text = @"暂无";
            }
        } else if([model.introduce isEqualToString:@"开放时间"]) {
            cell.contentLabel.text = model.opening_time;
            if (model.opening_time.length == 0) {
                cell.contentLabel.text = @"暂无";
            }
        } else if([model.introduce isEqualToString:@"联系方式"]) {
            cell.contentLabel.text = model.tel;
            if (model.tel.length == 0) {
                cell.contentLabel.text = @"暂无";
            }
        }
        return cell;
    }
    else {
        SpotSeparaCell *cell = [tableView dequeueReusableCellWithIdentifier:separator];
        if (cell == nil) {
            cell = [[[SpotSeparaCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:separator] autorelease];
            cell.blcok = ^(){
                TravelsForThisSpotViewController *travelInSpot = [[TravelsForThisSpotViewController alloc] init];
                travelInSpot.model = self.model;
                [self.navigationController pushViewController:travelInSpot animated:YES];
            };
        }
        return cell;
    }

}

- (void)tapAction:(UITapGestureRecognizer *)sender
{
    UIImageView *imageView = (UIImageView *)sender.view;
    
}
- (void)createImageView
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    NSDictionary *dic = [_dic objectForKey:@"share_args"];
    NSString *name = [_dic objectForKey:@"name"];
    NSNumber *wishCount = [_dic objectForKey:@"wish_to_go_count"];
    NSNumber *number = [_dic objectForKey:@"visited_count"];
    NSString *like = [NSString stringWithFormat:@"%@ 人去过 ／ %@ 人喜欢", number, wishCount];
    NSDictionary *subDic = [dic objectForKey:@"default"];
    NSString *str = [subDic objectForKey:@"shr_image"];
    self.imageView = [[CountryDetailImageView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 190)];
    [self.headerView addSubview:_imageView];
    [_imageView release];
    
    _imageView.likeLabel.text = like;
    [_imageView sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:image];
    
    UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(([[UIScreen mainScreen] bounds].size.width - 45) / 2, 190 - 45 / 2, 45, 45)];
    blankView.layer.cornerRadius = 45 / 2;
    blankView.backgroundColor = [UIColor whiteColor];
    [self.headerView addSubview:blankView];
    [blankView release];

    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(([[UIScreen mainScreen] bounds].size.width - 40) / 2, 170, 40, 40)];
    imageView.layer.cornerRadius = 20;
    imageView.layer.masksToBounds = YES;
    [imageView sd_setImageWithURL:[NSURL URLWithString:[_dic objectForKey:@"icon"]] placeholderImage:image];
    [self.headerView addSubview:imageView];
    [imageView release];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 210, [[UIScreen mainScreen] bounds].size.width, 40)];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = name;
    label.font = [UIFont boldSystemFontOfSize:30];
    [self.headerView addSubview:label];
    [label release];
    NSString *content = [_dic objectForKey:@"recommended_reason"];
    NSDictionary *tempDic = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
    
        
    if ([content isKindOfClass:[NSNull class]]) {
        content = [NSString stringWithFormat:@"%@", @"看来这是一个小编已经无法形容的奇妙的地方"];
    }
    CGRect rect = [content boundingRectWithSize:CGSizeMake([[UIScreen mainScreen] bounds].size.width - 120, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:tempDic context:nil];
    
    UILabel *contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(60, 260, [[UIScreen mainScreen] bounds].size.width - 120, rect.size.height)];
    
    contentLabel.font = [UIFont systemFontOfSize:13];
    contentLabel.text = content;
    contentLabel.numberOfLines = 0;
    contentLabel.textAlignment = NSTextAlignmentCenter;
    [self.headerView addSubview:contentLabel];
    [contentLabel release];
    
    UIColor *color = [UIColor colorWithRed:220 / 255.0 green:220 / 255.0 blue:220 / 255.0 alpha:1];
    
    UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 280 + rect.size.height, [[UIScreen mainScreen] bounds].size.width, 40)];
    [self.view addSubview:textLabel];
    textLabel.textAlignment = NSTextAlignmentCenter;
    textLabel.text = @"·游友印象·";
    textLabel.textColor = [UIColor colorWithRed:102 / 255.0 green:102 / 255.0 blue:153 / 255.0 alpha:1];
    textLabel.font = [UIFont systemFontOfSize:23];
    [self.headerView addSubview:textLabel];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(30, 301 + rect.size.height, 100, 1)];
    leftView.backgroundColor = color;
    [self.headerView addSubview:leftView];
    [leftView release];
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake([[UIScreen mainScreen] bounds].size.width - 130, 301 + rect.size.height, 100, 1)];
    rightView.backgroundColor = color;
    [self.headerView addSubview:rightView];
    [rightView release];
    [textLabel release];
    self.headerView.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 300 + rect.size.height);
    
}
@end
